#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/8/24 15:02
# @Author  : youfeng


from common.util import Util


class StatisticsService(object):
    # 代理总得存储
    __STATISTICS_TOTAL_REDIS_KEY = "proxy:statistics:total:{}"
    __STATISTICS_DAILY_REDIS_KEY = "proxy:statistics:{}:{}"

    # 每日切面到期时间
    __DAILY_EXPIRE_TIME = 14

    # 代理每日切面存储
    def __init__(self, proxy_dao, log=None):
        self.log = log
        self.__proxy_dao = proxy_dao

    # 获得每日切面 redis key
    def __get_daily_redis_key(self, tag):
        current_date = Util.get_current_date("%Y%m%d")
        return self.__STATISTICS_DAILY_REDIS_KEY.format(current_date, tag)

    # 获得总得代理数据redis key
    def __get_total_redis_key(self, tag):
        return self.__STATISTICS_TOTAL_REDIS_KEY.format(tag)

    # 获得到期时间
    def __get_expire_at_time(self):
        from datetime import datetime
        current_date = datetime.now()
        import datetime
        one_day = datetime.timedelta(days=self.__DAILY_EXPIRE_TIME)
        return current_date + one_day

    # 存储每日切面
    def save_daily_proxy(self, tag, proxy_list):
        redis_key = self.__get_daily_redis_key(tag)
        self.__proxy_dao.set_proxy_set_to_redis(redis_key, proxy_list)
        self.__proxy_dao.set_expire_time(redis_key, self.__get_expire_at_time())

    # 存储所有代理信息
    def save_total_proxy(self, tag, proxy_list):
        redis_key = self.__get_total_redis_key(tag)
        self.__proxy_dao.set_proxy_set_to_redis(redis_key, proxy_list)
